/*
 * @(#)org.example.netty.handler 2020/4/3/0003
 *
 * Copy Right@ 人人译视界
 */


package org.example.netty.protocoltcp;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.Charset;

/**
 * <pre>
 * @author tuwei
 *
 * @version 0.9
 *
 * 修改版本: 0.9
 * 修改日期: 2020/4/3/0003
 * 修改人 :  tuwei
 * 修改说明: 初步完成
 * 复审人 ：
 * </pre>
 */
public class MyClientHandler extends SimpleChannelInboundHandler<MessageProtocol> {

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		ctx.close();
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		// 使用客户端发送10条数据"今天天气冷，吃火锅"
		String msg2Send = "今天天气冷，吃火锅";
		byte[] content = msg2Send.getBytes(Charset.forName("utf-8"));
		int length = content.length;
		for (int i = 0; i < 5; i++) {
			MessageProtocol protocol = new MessageProtocol();
			protocol.setLength(length);
			protocol.setContent(content);
			ctx.writeAndFlush(protocol);
		}
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) throws Exception {
		System.out.println("客户端接收数据length=：" + msg.getLength());
		System.out.println("客户端接收数据content=：" + new String(msg.getContent(), Charset.forName("utf-8")));
	}
}
